package com.longshen.dubbo.api.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.longshen.dubbo.api.mapper.AdminUserMapper;
import com.longshen.dubbo.api.mapper.AdminUserRoleMapper;
import com.longshen.dubbo.api.model.AdminUser;
import com.longshen.dubbo.api.model.AdminUserRole;
import com.longshen.dubbo.api.sequence.SequenceService;
import com.longshen.dubbo.api.service.AdminUserService;

import tk.mybatis.mapper.entity.Example;

@Service
public class AdminUserServiceImpl implements AdminUserService {
	@Autowired
	private AdminUserMapper mapper;

	@Autowired
	private SequenceService seq;

	@Autowired
	private AdminUserRoleMapper userRoleMapper;

	@Override
	public AdminUser loginFind(String cellphone) {
		Example example = new Example(AdminUser.class);
		example.createCriteria().andEqualTo("cellphone", cellphone);
		return mapper.selectOneByExample(example);
	}

	@Override
	public AdminUser add(AdminUser in, String roleid) {
		in.setId(seq.getId());
		mapper.insert(in);
		AdminUserRole ur = new AdminUserRole();
		ur.setUserId(in.getId());
		ur.setRoleId(roleid);
		ur.setId(seq.getId());
		userRoleMapper.delete(ur);
		return in;

	}

	@Override
	public void addRole(String userid, String roleid) {
		AdminUserRole userRole = new AdminUserRole();
		userRole.setId(seq.getId());
		userRole.setRoleId(roleid);
		userRole.setUserId(userid);
		userRoleMapper.insert(userRole);
	}

	@Override
	public AdminUser findById(String userid) {
		return mapper.selectByPrimaryKey(userid);
	}

	@Override
	public Page<AdminUser> pageList(Integer pagesize, Integer pagenum, String username) {
		Example example = new Example(AdminUser.class);
		if (StringUtils.isNotBlank(username)) {
			username = "%" + username + "%";
			example.createCriteria().andLike("username", username);
		}
		example.setOrderByClause("id");
		Page<AdminUser> page = PageHelper.startPage(pagenum, pagesize)
				.doSelectPage(() -> mapper.selectByExample(example));
		return page;
	}

	@Override
	public void delById(String id) {
		mapper.deleteByPrimaryKey(id);
	}

	@Override
	public AdminUser mod(AdminUser in, String roleid) {
		mapper.updateByPrimaryKeySelective(in);
		AdminUserRole ur = new AdminUserRole();
		ur.setRoleId(roleid);
		ur.setUserId(in.getId());
		userRoleMapper.delete(ur);
		ur.setId(seq.getId());
		userRoleMapper.insert(ur);
		return in;
	}

}
